package com.tengju.support.infrastructure.repository.rule;

import com.tengju.support.domain.model.rule.Rule;
import com.tengju.support.domain.model.rule.RuleId;
import com.tengju.support.domain.model.rule.RuleRepository;
import com.tengju.support.infrastructure.persistence.mybatis.dataobject.SupportRuleDO;
import com.tengju.support.infrastructure.persistence.mybatis.mapper.tengju.custom.RuleMapper;
import com.tengju.support.infrastructure.persistence.redis.RuleCacheRepository;
import com.tengju.support.infrastructure.repository.rule.convert.RuleConvert;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Repository
public class RuleRepositoryImpl implements RuleRepository {

    @Resource
    RuleMapper ruleMapper;

    @Resource
    RuleCacheRepository ruleCacheRepository;

    @Override
    public void store(Rule rule) {
        SupportRuleDO supportRuleDO = RuleConvert.convertToDO(rule);
        ruleMapper.store(supportRuleDO);
    }

    @Override
    @Transactional(value = "dealerTransactionManager",rollbackFor = Exception.class)
    public void updateByRule(Rule rule) {
        SupportRuleDO supportRuleDO = RuleConvert.convertToDO(rule);
        int result = ruleMapper.updateByRuleId(supportRuleDO);
        if (result == 1) {
            ruleCacheRepository.deleteRule(rule.getRuleId());
        }
    }

    @Override
    public Rule queryRule(RuleId ruleId) {
        Rule rule = ruleCacheRepository.getRule(ruleId);
        if (rule == null) {
            SupportRuleDO ruleDO = ruleMapper.queryRuleById(ruleId.getValue());
            rule = RuleConvert.convertToModel(ruleDO);
            ruleCacheRepository.cacheRule(rule);
        }
        return rule;
    }

}
